/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
#include <cstdlib>
class Partition {
public:
    ListNode* partition(ListNode* pHead, int x) {
        // write code here
        struct ListNode* minhead, * maxhead, * mintail, * maxtail;
        minhead = mintail = (struct ListNode*)malloc(sizeof(struct ListNode));
        maxhead = maxtail = (struct ListNode*)malloc(sizeof(struct ListNode));
        struct ListNode* cur = pHead;
        while (cur)
        {
            if (cur->val < x)
            {
                mintail->next = cur;
                mintail = mintail->next;
            }
            else
            {
                maxtail->next = cur;
                maxtail = maxtail->next;
            }
            cur = cur->next;
        }
        mintail->next = maxhead->next;
        maxtail->next = NULL;
        struct ListNode* head = minhead->next;
        free(minhead);
        free(maxhead);
        return head;
    }
};